package com.web.farme.meta;


import com.web.farme.annotation.Column;
import com.web.farme.annotation.Table;
import lombok.Data;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

@Data
public class TableInfo {


    private String auto;

    private String tableName;

    private Class<?> entityClass;

    private String engine;

    private String charset;

    private String comment;

    private Integer databaseSize;

    private Integer tableSize;

    private String shardKey;

    private String primaryKey;

    private Field primaryKeyField;

    private Class<?> primaryKeyFieldClass;

    private Map<String, TableFieldInfo> tableFieldInfos;

    public TableInfo(Class<?> entityClass) {
        this.entityClass = entityClass;
    }

    /**
     * 处理表
     */
    public void tableHandle() {

        Table annotation = this.entityClass.getAnnotation(Table.class);
        this.tableName = annotation.value();
        //如果注解没有写name 那么弄一个根据类名驼峰转下划线方法创建表

        //处理引擎 默认innodb
        this.engine = annotation.engine();
        //处理字符编码
        this.charset = annotation.charset();
        //处理注释
        this.comment = annotation.comment();
        //数据库个数
        this.databaseSize = annotation.databaseSize();
        //表个数
        this.tableSize = annotation.tableSize();
        //分库分表字段
        this.shardKey = annotation.shardingColumn();
        //处理字段
        tableFieldInfos = new HashMap<>();
        Field[] fields = entityClass.getDeclaredFields();
        for (Field field : fields) {
            if (!field.isAnnotationPresent(Column.class)) {
                continue;
            }
            field.setAccessible(true);
            Column fieldAnnotation = field.getAnnotation(Column.class);
            TableFieldInfo tableFieldInfo = new TableFieldInfo();
            tableFieldInfo.setField(field);
            tableFieldInfo.setFieldName(field.getName());
            tableFieldInfo.setFieldClass(field.getType());
            tableFieldInfo.setColumnName(fieldAnnotation.columnName());
            tableFieldInfo.setColumnType(fieldAnnotation.jdbcType().name());
            tableFieldInfo.setLength(fieldAnnotation.length());
            tableFieldInfo.setNull(fieldAnnotation.isNull());
            tableFieldInfo.setComment(fieldAnnotation.comment());
            tableFieldInfo.setColumnDefault(fieldAnnotation.columnDefault());
            //如果没写name 就字段驼峰转下划线
            tableFieldInfo.setColumnName(tableFieldInfo.getColumnName().toLowerCase());
            if(fieldAnnotation.isPrimaryKey())
            {
                this.primaryKey = tableFieldInfo.getColumnName();
                this.primaryKeyField = field;
                this.primaryKeyFieldClass = field.getType();
                tableFieldInfo.setPrimaryKey(true);
            }
            tableFieldInfos.put(tableFieldInfo.getColumnName(), tableFieldInfo);
         }
    }


}
